package com.bingxue.edu.framework.config;

import com.bingxue.edu.management.system.service.ConfigService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.sms4j.core.factory.SmsFactory;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 动态配置加载器
 *
 * @author panbo
 * @since 2024/07/24
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class DynamicConfigLoader implements ApplicationRunner {

    private final ConfigService configService;
    private final DynamicConfigRefresher dynamicConfigRefresher;
    private final SmsDynamicConfig smsDynamicConfig;

    @Override
    public void run(ApplicationArguments args) {
        reload();
    }

    /**
     * 重新加载配置，并加载相关联的配置
     */
    public void reload() {
        refresh();
        SmsFactory.reloadAll(smsDynamicConfig);
    }

    /**
     * 定时刷新springboot 配置
     * 暂时只会刷新environment配置和@ConfigurationProperties配置，@Value配置不会刷新
     */
    @Scheduled(fixedRate = 1, timeUnit = TimeUnit.MINUTES, initialDelay = 10 * 1000)
    public void refresh() {
        Map<String, Object> newValues = configService.listDynamicConfigMap();
        dynamicConfigRefresher.refresh(newValues);
    }
}
